package com.qf.web.controller;

import com.qf.pojo.Admin;
import com.qf.pojo.ReaderInfo;
import com.qf.service.AdminService;
import com.qf.service.ReaderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class LoginController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private ReaderInfoService readerInfoService;
    @GetMapping({"/","/tologinui","/login.html"})
    public String toLogUI(){
        return "index";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping({"/api/loginCheck"})
    @ResponseBody
    public Map<String,String> loginCheck(String username, String password, HttpSession session){
        log.info("username:{} --->" + username);
        log.info("password:{} --->" + password);

        Map<String,String> map = new HashMap<>();

        try {
            //管理员登录
            Admin admin = adminService.login(username, password);
            session.setAttribute("admin",admin);
            map.put("stateCode","1");
        } catch (Exception e) {
            e.printStackTrace();
            //借阅人登录
            try {

                ReaderInfo readerInfo = readerInfoService.login(username, password);
                session.setAttribute("readerInfo",readerInfo);
                map.put("stateCode","2");
            } catch (Exception ex) {
                ex.printStackTrace();
                map.put("stateCode","0");
            }
        }
        return map;
    }

    @GetMapping("/logout.html")
    public String logout(HttpSession session){
        session.invalidate();
        return "index";
    }
}
